package com.sky.controlor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.sky.mapper.model.User;
import com.sky.service.UserService;

@Controller
@RequestMapping(value="/user")
public class LoginControlor  extends SuperControlor {
	
	@Resource
	private UserService userServiceImpl;
	
		/**
		 * 执行删除
		 * @param uid
		 * @return
		 */
		@RequestMapping(value="/delete{uid}.shtml",method=RequestMethod.GET)
		public String  delete(@PathVariable(value="uid")int uid){
			
			userServiceImpl.delete(uid);
			
			return "redirect:/user/list.shtml";
		}
	
	/**
	 * 到修改页面
	 * @param uid
	 * @return
	 */
	@RequestMapping(value="/update.shtml",method=RequestMethod.GET)
	public ModelAndView update(@RequestParam(value="uid")int uid){
		
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("uid",uid);
		//根据uid查询
		List<User> userList = userServiceImpl.query(param);
		//转到的逻辑视图
		ModelAndView mv = new ModelAndView("update");
		//把查询的结果传到对应的视图中
		mv.addObject("users", userList.get(0));
		
		return mv;
	}
	
	
	/**
	 * 执行修改
	 * @param u
	 * @return
	 */
	@RequestMapping(value="/update.shtml",method=RequestMethod.POST)
	public String  update(User u){
		
		userServiceImpl.update(u);
		
		return "redirect:/user/list.shtml";
	}
	
	/**
	 * 去到add的jsp页面
	 * @return
	 */
	@RequestMapping(value="/add.shtml",method=RequestMethod.GET)
	public String add(){
		return "add";
	}
	
	/**
	 * 添加用户
	 * @param u
	 * @return
	 */
	@RequestMapping(value="/add.shtml",method=RequestMethod.POST)
	public String add(User u){
		
		userServiceImpl.add(u);
		//跳转到list方法去
		return "redirect:/user/list.shtml";
	}
	/**
	 * 查询所有用户
	 * @param u 
	 * @param m 
	 * @return 
	 */
	@RequestMapping(value="/list.shtml")
	//@RequestParam(value="u",required=false)User接收的参数User类型的u，required=false不是必须的
	public String list(@RequestParam(value="uname",required=false)String uname,Model m){
		//把参数放在map中（可以存空值）
		Map<String, Object> param = new HashMap<String,Object>();
		param.put("uname", uname);
		//有参数就根据参数查询，没有参数就查询所有
		List<User> listUser =userServiceImpl.query(param);
		//把查到的数据封装到model中传递到前端jsp
		m.addAttribute("listUser", listUser);
		return "listUser";
	}
	
	
}
